package com.century.sjt.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Message;
import android.text.format.Time;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.EMChat.domain.Translate;
import com.century.sjt.R;
import com.century.sjt.activity.login.ChooseLanguageActivity;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by asus on 2016/9/2.
 */
public class TranslateActivity extends BaseActivity{
    private TextView icon_translation,icon_time;
    private TextView tvTime;
    private LinearLayout layoutOpen;
    private SjtTitleBar titleBar;
    private LinearLayout layoutSelect_language;
    private LinearLayout layoutOpenServer;
    private String userId,isTrans,transLanguage;
    SharedPreferences mainSharedPreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.translate_activity);

        initView();
        initEvent();
        initData();
    }
    @Override
    protected void onResume() {
        transInfoDetail();
        super.onResume();
    }
    @Override
    protected void initView() {
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        //       标题栏
        titleBar.setTitle(getResources().getString(R.string.text_translate_service));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvTime = (TextView) findViewById(R.id.translate_time);
        icon_translation = (TextView) findViewById(R.id.icon_translation);
        icon_time = (TextView) findViewById(R.id.icon_time);
        layoutOpen = (LinearLayout) findViewById(R.id.ll_open_translate);
        layoutSelect_language = (LinearLayout) findViewById(R.id.translate_select_language);
        layoutOpenServer = (LinearLayout) findViewById(R.id.translate_server);
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        icon_translation.setTypeface(iconfont);
        icon_time.setTypeface(iconfont);
        tvTime.setText(getTime());

    }

    @Override
    protected void initEvent() {
        layoutOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                orderTranslation();
            }
        });
        layoutSelect_language.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(TranslateActivity.this, ChooseLanguageActivity.class);
                intent.putExtra("type","Translate");
                startActivityForResult(intent,Constant.REQUESTCODE_LANGUAGE);
            }
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==RESULT_OK){
            switch (requestCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
                case Constant.REQUESTCODE_LANGUAGE:

                    break;
                default:
                    break;
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }
    @Override
    protected void initData() {
        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        userId = mainSharedPreferences.getString("userId", "");
        isTrans = mainSharedPreferences.getString("isTrans","");
        transLanguage = mainSharedPreferences.getString("transLanguage","");

        if ("1".equals(isTrans)){
            layoutOpenServer.setVisibility(View.GONE);
            layoutSelect_language.setVisibility(View.VISIBLE);
        }else {
            layoutOpenServer.setVisibility(View.VISIBLE);
            layoutSelect_language.setVisibility(View.GONE);
        }
    }

    public String getTime(){
        String nowTime = "" ;
        Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料

        t.setToNow(); // 取得系统时间。

        int year = t.year;

        int month = t.month + 1;

        int date = t.monthDay;

        int hour = t.hour;    // 0-23
        nowTime = year + "." + month + "." + date + "-" + (year+1) + "." + month + "." + date;
        return nowTime;
    }


    private void orderTranslation() {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), TranslateActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.orderTranslation, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject data = res.getJSONObject("data");
                    if (code.equals("407")){
                        TipUtil.showAppayRes(TranslateActivity.this);
                    }
                    if (code.equals("200")) {//成功
                        String orderId = data.getString("orderid");
                        Intent intent = new Intent(TranslateActivity.this, MyOrderDetailsActivity.class);
                        intent.putExtra("orderId", orderId);
                        intent.putExtra("falg",3);
                        startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message, TranslateActivity.this, 1);
                    }
                    TipUtil.closeProgressDialog();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), TranslateActivity.this, 1);

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), TranslateActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("userIds",userId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    //翻译查询

    private void transInfoDetail() {
        TipUtil.openProgressDialog(com.century.sjt.util.Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), TranslateActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.transInfo, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject aData = res.getJSONObject("data");
                        String hasTransService = aData.getString("hasTransService");
                        if ("1".equals(hasTransService)){
                            String startDate = aData.getString("startDate");
                            String endDate = aData.getString("endDate");
                            tvTime.setText(startDate+"-"+endDate);
                            if ("0".equals(isTrans)){
                                SharedPreferences.Editor editor = mainSharedPreferences.edit();
                                editor.putString("isTrans", hasTransService);
                                editor.commit();
                            }
                        }

                    } else {//失败
                        TipUtil.showToast(message, TranslateActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service),TranslateActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), TranslateActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }
}
